<template>
  <div class="qs-chart"></div>
</template>

<script>
import echarts from 'echarts'
import { debounce } from '@/util'

function buildOption(seriesName, names, values, text, subtext = undefined) {
  const seriesData = []
  const selected = {}
  for (let i = 0; i < names.length; i++) {
    const name = names[i]
    const value = values[i]
    selected[name] = true
    seriesData.push({
      name,
      value
    })
  }
  return {
    title: {
      text: text,
      subtext: subtext,
      x: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)'
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: 10,
      top: 20,
      bottom: 20,
      data: names,
      selected: selected
    },
    series: [
      {
        name: seriesName,
        type: 'pie',
        radius: '55%',
        center: ['40%', '50%'],
        data: seriesData,
        itemStyle: {
          emphasis: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
}

export default {
  name: 'PieChartByStatus',
  props: {
    source: {
      type: Array,
      required: true
    },
    title: {
      type: String,
      default: '审核状况统计'
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    source() {
      this.destroy()
      this.create()
    }
  },
  mounted() {
    this.create()
  },
  beforeDestroy() {
    this.destroy()
  },
  methods: {
    create() {
      this.initChart()
      this.__resizeHandler = debounce(() => {
        if (this.chart) {
          this.chart.resize()
        }
      }, 100)
      window.addEventListener('resize', this.__resizeHandler)
    },
    destroy() {
      if (!this.chart) {
        return
      }
      window.removeEventListener('resize', this.__resizeHandler)
      this.chart.dispose()
      this.chart = null
    },
    initChart() {
      const chart = this.chart = echarts.init(this.$el, 'macarons')

      const source = this.source
      const title = this.title
      const names = source.map(item => item.name)
      const values = source.map(item => item.count)

      chart.setOption(buildOption('审核结果', names, values, title))
    }
  }
}
</script>
